package cn.tqfeiyang.smartadmin.business.organization.service;

import cn.tqfeiyang.smartadmin.business.organization.entity.DepartmentEntity;
import cn.tqfeiyang.smartadmin.business.organization.mapper.DepartmentMapper;
import cn.tqfeiyang.smartadmin.business.organization.request.DepartmentQueryDTO;
import cn.tqfeiyang.smartadmin.business.organization.request.DepartmentCreateDTO;
import cn.tqfeiyang.smartadmin.business.organization.response.DepartmentQueryVO;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;
import jakarta.annotation.Resource;

import cn.tqfeiyang.smartadmin.commons.toolbox.ExcelUtils;
import cn.tqfeiyang.smartadmin.commons.toolbox.BeanUtils;
import cn.tqfeiyang.smartadmin.commons.toolbox.ValidationUtils;
import cn.tqfeiyang.smartadmin.commons.mybatis.EntityBroadcast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 部门Excel服务
 *
 * @author tqfeiyang
 * @since 2024-10-18
 */
@Service
public class DepartmentExcelService {

    /**
     * 实体广播对象
     */
    @Resource
    private EntityBroadcast entityBroadcast;

    /**
     * 部门映射接口
     */
    @Resource
    private DepartmentMapper departmentMapper;

    /**
     * 导出Excel
     *
     * @param dto 请求数据
     */
    public void exportDepartmentsToExcel(DepartmentQueryDTO dto) {
        Assert.notNull(dto, "dto不能为空");
        List<DepartmentQueryVO> list = departmentMapper.queryDepartments(dto);
        ExcelUtils.exportExcel(list, DepartmentQueryVO.class, "部门");
    }

    /**
     * 下载模板
     */
    public void downloadDepartmentTemplate() {
        List<DepartmentEntity> list = Arrays.asList(new DepartmentEntity());
        ExcelUtils.exportExcel(list, DepartmentCreateDTO.class, "部门模板");
    }

    /**
     * 导入Excel
     *
     * @param file 导入文件
     */
    @Transactional(rollbackFor = Exception.class)
    public void importDepartmentsFromExcel(MultipartFile file) {
        Assert.notNull(file, "file不能为空");
        ReadListener<DepartmentCreateDTO> listener = new ReadListener<>() {
            @Override
            public void invoke(DepartmentCreateDTO dto, AnalysisContext context) {
                ValidationUtils.validateProperties(dto);

                DepartmentEntity entity = BeanUtils.copy(dto, DepartmentEntity.class);
                entityBroadcast.validate(entity, true);

                departmentMapper.insert(entity);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                entityBroadcast.clearCache(DepartmentEntity.class);
            }
        };
        ExcelUtils.importExcel(file, DepartmentCreateDTO.class, listener);
    }
}
